package com.ffspace.web;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ff.blog.common.BaseResult;
import com.ff.blog.enums.ActionType;
import com.ffspace.blog.core.dal.dataobject.User;
import com.ffspace.blog.service.UserService;

@Controller
public class UserController {
	
	private static Logger	logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserService userService;
	
	@ResponseBody
	@RequestMapping("/login.htm")
	public BaseResult<User> login(HttpServletRequest request) throws Exception
	{
		String loginName = request.getParameter("loginName");
		String password = request.getParameter("password");
		BaseResult<User> result = userService.login(loginName, password);
		
		if (result.isSuccess())
		{
			request.getSession().setAttribute("userInfo", result.getData());
		}
		
		return result;
	}

	@ResponseBody
	@RequestMapping("/register.htm")
	public BaseResult<User> register(HttpServletRequest request) throws Exception
	{
		BaseResult<User> result = new BaseResult<User>();
		try
		{
			String loginName = request.getParameter("loginName");
			String password = request.getParameter("password");
			String nickName = request.getParameter("nickName");
			String email = request.getParameter("email");
	
			User user = new User();
			user.setEmail(email);
			user.setLoginName(loginName);
			user.setNickName(nickName);
			user.setPassword(password);
			userService.register(user);
			
			result.setSuccess(true);
			result.setMessage("注册成功");
		}
		catch (Exception e)
		{
			logger.error("active error", e);
			result.setSuccess(false);
			result.setMessage("服务器错误");
		}
		return result;
	}
	

	@RequestMapping("/active.htm")
	public String active(HttpServletRequest request, ModelMap model) throws Exception
	{
		model.addAttribute("type", ActionType.ACTIVE.getCode());
		String token = request.getParameter("token");

		BaseResult<String>	result = userService.active(token);
		if (result.isSuccess())
		{
			return "success";
		}

		return "error";
	}
	
	@RequestMapping("/forwardSuccess.htm")
	public String forwardSuccess(HttpServletRequest request, String type, ModelMap model) throws Exception
	{
		model.addAttribute("type", type);

		return "success";

	}
	
}
